/**
 * Copyright &copy; 2017-2018 <a href="http://www.webcsn.com">webcsn</a> All rights reserved.
 *
 * @author hermit
 * @date 2018-04-17 10:54:58
 */
package com.wxmp.wxcms.ctrl;

import com.wxmp.core.annotation.IgnoreSecurity;
import com.wxmp.core.common.BaseCtrl;
import com.wxmp.core.common.Constants;
import com.wxmp.core.util.AjaxResult;
import com.wxmp.core.util.HttpConnectionUtil;
import com.wxmp.core.util.MyGetLocation;
import com.wxmp.core.util.SessionUtil;
import com.wxmp.wxapi.process.MpAccount;
import com.wxmp.wxapi.process.WxMemoryCacheClient;
import com.wxmp.wxcms.domain.RegisterUser;
import com.wxmp.wxcms.service.AccountService;
import com.wxmp.wxcms.service.RegisterUserService;
import com.wxmp.wxcms.service.TokenService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
/**
 *
 * @author fuziKong
 * @version 2.0
 * @date 2018-06-06 10:54:58
 */
@RestController
@RequestMapping("/regUser")
public class RegisterUserCtrl extends BaseCtrl {

	@Autowired
	private RegisterUserService entityService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private AccountService accountService;
	private static final Logger log = Logger.getLogger(RegisterUserCtrl.class);
	/**
	 * 发送手机验证码
	 * @param phone
	 * @return
	 */
	@RequestMapping(value = "/validateCode", method = RequestMethod.GET,produces = "application/json; charset=UTF-8")
	public AjaxResult validateCode(String phone,HttpSession session) {
		 	String host = "https://feginesms.market.alicloudapi.com";
		    String path = "/codeNotice";
		    String appcode = "70e36824d8ba401f9c06ba4d42588ef5";
		    Map<String, String> headers = new HashMap<String, String>();
		    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		    headers.put("Authorization", "APPCODE " + appcode);
		    Map<String, String> querys = new HashMap<String, String>();
		    String code = new Random().nextInt(1000000) + "";
//		    SessionUtil.setAttr("code",code);
		    session.setAttribute("code",code);
		    querys.put("param", code);
		    querys.put("phone", phone);
		    querys.put("sign", "43857");
		    querys.put("skin", "33820");

		    String res =HttpConnectionUtil.get(host+path, headers, querys);
		    return AjaxResult.success(res);
	} 
	/**
	 * @description 用户登录
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
	public AjaxResult login(RegisterUser user) {
		//user.setPwd(MD5Util.getMD5Code(user.getPwd()));
		RegisterUser registerUser = this.entityService.getRegisterUser(user);
		if (registerUser == null) {
			return AjaxResult.failure("用户名或者密码错误");
		}
		String token = tokenService.createToken(user.getName());
		log.debug("************** Generate Token ******************** : " + token);
		Cookie cookie = new Cookie(Constants.DEFAULT_TOKEN_NAME, token);
		log.debug("Write Token to Cookie and return to the Client : " + cookie.toString());
		response.addCookie(cookie);
		SessionUtil.setRegisterUser(registerUser);
		return AjaxResult.success(registerUser.getNickName());
	}
	/**     
	 * @description 登出处理
	 * @created 2018年06月06日 下午4:53:58   
	 * @param request
	 * @return  
	 */
	@RequestMapping(method = RequestMethod.DELETE)
	@IgnoreSecurity
	public AjaxResult logout(HttpServletRequest request) {
		String token = request.getHeader(Constants.DEFAULT_TOKEN_NAME);
		tokenService.deleteToken(token);
		log.debug("Logout Success...");
		return AjaxResult.success("Logout Success...");
	}
	/**
	 * 根据Id查询用户分享
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getById")
	public AjaxResult getById(Integer id){
		RegisterUser registerUser =  entityService.getById(id);
		return AjaxResult.success(registerUser);
	}

	
	/**
	 * 分页查询
	 * @param searchEntity
	 * @return
	 */
	@RequestMapping(value = "/listForPage",method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
	public AjaxResult listForPage(RegisterUser searchEntity) {
		List<RegisterUser> list = entityService.getRegUserListByPage(searchEntity);
		if (CollectionUtils.isEmpty(list)) {
			return AjaxResult.success();
		}
		return getResult(searchEntity,list);
	}
	
	/**
	 * 绑定手机号
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/updatePhone",method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
	public AjaxResult updatePhone(RegisterUser entity,HttpSession session){
	    Object objCode =  session.getAttribute("code");//SessionUtil.getAttr("code");
	    String code =  objCode!=null ? objCode.toString() : "";

		entity.setAddress(MyGetLocation.getAdd(entity.getLat(),entity.getLog()));
		log.debug("绑定手机号====entity========"  + entity);
	    int result = entityService.updatePhone(entity);
	   	if(result >0) {
	   		return AjaxResult.success("手机号绑定成功。");
	   	}else {
	   		return AjaxResult.failure("手机号绑定失败，请联系系统管理员。");
	   	}
	    
	    /*
	    if(entity.getValidateCode() != null && !entity.getValidateCode().equals(code) ) {
	    	return AjaxResult.failure("0","验证码输入错误！");
	    }else {
	    	int result = entityService.updatePhone(entity);
	    	 log.info("绑定手机号====result========"  + result);
	    	if(result >0) {
	    		return AjaxResult.success("1", "手机号绑定成功。");
	    	}else {
	    		return AjaxResult.failure("2", "手机号绑定失败，请联系系统管理员。");
	    	}
	    }
	    */
	}

	/**
	 * 根据 openId 查询用户
	 * @param openid
	 * @return RegisterUser
	 */
	@RequestMapping(value = "/getUserByOpenId",method = RequestMethod.GET,produces = "application/json; charset=UTF-8")
	public RegisterUser getUserByOpenId(String openid) {
        log.debug("===[UserCalcCtrl.getUserByOpenId]===openid=="+openid);
		RegisterUser regUser = entityService.getByOpenId(openid);
		return regUser;
	}
	
	

	/**
	 * 修改/添加
	 * @param entity
     * @return AjaxResult
     */
	@RequestMapping(value = "/update")
	public AjaxResult update(RegisterUser entity){
		log.debug("===[RegisterUserCtrl.update]==用户注册============"  + entity);
		if (entity.getId() != null) {
			entityService.update(entity);
			//更新成功
			return AjaxResult.updateSuccess();
		} else {	
			boolean  tt = entityService.userExists(entity.getOpenid());
			if( ! tt ) {
				entity.setEndTime(new Date());
				entityService.add(entity);
				return AjaxResult.success("用户注册成功!");
			}else {
				return AjaxResult.failure("用户已存在.");
			}
		}
	}


	/**
	 * 分享
	 * @param openId
	 * @return AjaxResult
	 */
	@RequestMapping(value = "/share",method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
	public AjaxResult share(String openId) {
		log.debug("===[RegisterUserCtrl.share]==用户分享======="+openId);
		//分享成功延长试用天数
		MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();//获取缓存中的唯一账号
		Integer addDays = accountService.getAddDays(mpAccount.getAccount());
		int day = entityService.updateUseDay(addDays, openId);
		log.debug("===[RegisterUserCtrl.share]==用户分享结果===="+day);
		if(day>0){
			return AjaxResult.success(null,"恭喜你分享成功，延长试用期1天。","1");
		}else {
			return AjaxResult.success(null,"分享失败!","0");
		}


	}
	/**
	 * 删除
	 * @param entity
	 * @return AjaxResult
	 */
	@RequestMapping(value = "/deleteById")
	public AjaxResult deleteById(RegisterUser entity) {
		entityService.delete(entity);
		return AjaxResult.deleteSuccess();
	}
	
	/**
	 * 批量删除
	 * @param  ids
	 * @return AjaxResult
	 */
	@RequestMapping(value = "/deleteBatchIds")
	public AjaxResult deleteBatchIds(String [] ids) {
		entityService.deleteBatchIds(ids);
		return AjaxResult.deleteSuccess();
	}
}